package com.tanhua.management.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.management.mapper.LogMapper;
import com.tanhua.management.mapper.UserMapper;
import com.tanhua.management.mapper.UsersInfoMapper;
import com.tanhua.management.pojo.Log;
import com.tanhua.management.pojo.User;
import com.tanhua.management.pojo.UserFreeze;
import com.tanhua.management.pojo.UserInfo;
import com.tanhua.management.utils.UserThreadLocal;
import com.tanhua.management.vo.PageResult;
import com.tanhua.management.vo.UsersVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: PeiLin·Wang
 * @Description: 类说明
 * @Date: Created in 11:30 2021/1/17
 * @ModifiedBy:
 */
@Service
public class UsersService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UsersInfoMapper usersInfoMapper;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private static final String FREEZE_PREFIX="FREEZE_";
    /**
     * 用户数据翻页
     *
     * @param page
     * @param pageSize
     * @param id
     * @param nickName
     * @param city
     * @param token
     * @return
     */
    public PageResult queryByPage(Integer page, Integer pageSize, Long id, String nickName, String city, String token) {

        //创建分页对象设置参数
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        //设置模糊查询条件
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        if (null != id) {
            queryWrapper.eq("user_id", id);
        }
        if (StringUtils.isNotEmpty(nickName)) {
            queryWrapper.eq("nick_name", nickName);
        }
        if (StringUtils.isNotEmpty(city)) {
            queryWrapper.eq("city", city);
        }
        //查询数据总条数
        Integer count = this.usersInfoMapper.selectCount(queryWrapper);
        //填充基本信息
        List<UserInfo> userInfoList = this.usersInfoMapper.selectList(queryWrapper);
        List<UsersVo> usersVoList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            UsersVo usersVo = new UsersVo();
            usersVo.setId(userInfo.getId());
            usersVo.setNickname(userInfo.getNickName());
            usersVo.setSex(userInfo.getSex() == 1 ? "男" : "女");
            usersVo.setCity(userInfo.getCity());
            //获取用户状态
            String key=FREEZE_PREFIX+userInfo.getUserId();
            Boolean s = this.redisTemplate.hasKey(key);
            if(!s){
                usersVo.setUserStatus("1");
            }else {
                usersVo.setUserStatus("2");
            }

            //最近活跃时间
            //通过用户id查询该用户的最近活跃时间(最后登录时间)
            Log log = logMapper.selectById(userInfo.getUserId());
            //如果没有查到最后登录时间的数据(即注册后为登录)则使用注册时间为最后活跃时间
            if(null != log){
                usersVo.setLastActiveTime(log.getLogTime().getTime());
            } else {
                usersVo.setLastActiveTime(userInfo.getCreated().getTime());
            }
            usersVoList.add(usersVo);
        }
        pageResult.setItems(usersVoList);
        pageResult.setCounts(count);
        return pageResult;
    }

    /**
     * 用户基本资料
     *
     * @param userId
     * @return
     */
    public UsersVo queryUserInfoById(Long userId) {
        UsersVo usersVo = new UsersVo();

        //根据id查询用户信息
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getUserId, userId);
        UserInfo userInfo = this.usersInfoMapper.selectOne(queryWrapper);
        if(userInfo != null){
            //填充数据到usersVo
            usersVo.setId(userInfo.getUserId());
            usersVo.setMobile(this.userMapper.selectOne(new QueryWrapper<User>().eq("id", userId)).getMobile());
            usersVo.setCountBeLiked(this.userLikeApi.queryFanCount(userId).intValue());//被喜欢数
            usersVo.setCountLiked(this.userLikeApi.queryLikeCount(userId).intValue());//喜欢人数
            usersVo.setCountMatching(this.userLikeApi.queryEachLikeCount(userId).intValue());//配对人数
            usersVo.setNickname(userInfo.getNickName());//昵称
            usersVo.setSex(userInfo.getSex() == 1 ? "男" : "女");//性别
            usersVo.setAge(userInfo.getAge());//年龄
            usersVo.setIncome(Integer.parseInt(userInfo.getIncome()));//收入
            usersVo.setOccupation(userInfo.getIndustry());//职业
            usersVo.setCity(userInfo.getCity());//注册地区
            usersVo.setLogo(userInfo.getLogo());//头像
            String key=FREEZE_PREFIX+userInfo.getUserId();
            String s = this.redisTemplate.opsForValue().get(key);
            if(null == s){
                usersVo.setUserStatus("1");
            }else {
                usersVo.setUserStatus("2");
            }
            usersVo.setCreated(userInfo.getCreated().getTime());//注册时间
            usersVo.setTags(userInfo.getTags());// 用户标签
            usersVo.setPersonalSignature("风吹稻花香");// 个性签名
            //通过用户id查询该用户的最近活跃时间(最后登录时间)
            Log log = logMapper.selectById(userInfo.getUserId());
            //如果没有查到最后登录时间的数据(即注册后为登录)则使用注册时间为最后活跃时间
            if(null != log){
                usersVo.setLastActiveTime(log.getLogTime().getTime());
            } else {
                usersVo.setLastActiveTime(userInfo.getCreated().getTime());
            }
            usersVo.setLastLoginLocation(this.logMapper.selectById(userInfo.getUserId()).getPlace());//todo 最近登录地点

            return usersVo;
        }

        return null;
    }

}
